package p.ithorns.sample.refresh;

import lombok.Getter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * ConfigChangeListener
 * TODO
 *
 * @author HtL
 * @date 2025/3/14 14:52
 * @since 1.0.0
 */

@Component
public class ConfigChangeListener implements ApplicationListener<ConfigChangeListener.RefreshEvent> {

    private final ApplicationContext appCtx;

    public ConfigChangeListener(ApplicationContext appCtx) {
        this.appCtx = appCtx;
    }

    @Override
    public void onApplicationEvent(RefreshEvent event) {
    }

    public void refreshConfig(Map<String, Object> properties) {
        // 刷新MutablePropertySources
        ConfigContext.refreshConfig(properties);
        appCtx.publishEvent(new RefreshEvent(Thread.currentThread().getStackTrace()[0], properties));
    }

    @Getter
    static class RefreshEvent extends ApplicationEvent {

        private Map<String, Object> params;

        public RefreshEvent(Object source, Map<String, Object> params) {
            super(source);
            this.params = params;
        }
    }
}
